package com.hainatong.shiphelper.module.holiday.fragment;

import android.os.Bundle;
import android.view.View;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.hainatong.shiphelper.GlobalConfig;
import com.hainatong.shiphelper.MvvmLazyFragment;
import com.hainatong.shiphelper.R;
import com.hainatong.shiphelper.databinding.FragmentNormalHolidayBinding;
import com.hainatong.shiphelper.module.holiday.PortActivity;
import com.hainatong.shiphelper.module.holiday.entity.DictFunBean;
import com.hainatong.shiphelper.module.holiday.entity.HolidayTypeBean;
import com.hainatong.shiphelper.module.holiday.entity.PortBean;
import com.hainatong.shiphelper.module.holiday.entity.VacationParam;
import com.hainatong.shiphelper.module.holiday.viewmodel.VacationViewModel;
import com.hainatong.shiphelper.utils.ComDataUtils;
import com.hainatong.shiphelper.utils.GsonUtil;
import com.hainatong.shiphelper.utils.PushToast;
import com.hainatong.shiphelper.utils.TimeUtil;
import com.hainatong.shiphelper.widget.LoadingDialog;
import com.hainatong.shiphelper.widget.PickerDialog;
import com.hainatong.shiphelper.widget.datapicker.CustomDatePicker;
import com.jeremyliao.liveeventbus.LiveEventBus;

import java.util.ArrayList;
import java.util.List;

/**
 *  提交 休假
 */
public class NormalHolidayFragment extends MvvmLazyFragment<FragmentNormalHolidayBinding, VacationViewModel>
{
    private static String HOLIDAY_TAG = "NormalHolidayFragment";

    public static int  normalHolidayType = 1;
    public static int  tempHolidayType = 2;
    public static int  delayHolidayType = 3;
    public static int  changeHolidayType = 4;

    private int holidayType;
    private int timeTag = 0;
    private CustomDatePicker datePicker;

    private PickerDialog pickerDialog;

    private VacationParam vacParam;

    private LoadingDialog loading;

    private HolidayTypeBean mHolidayType;

    private PortBean selectPort;

    private int pickTag = 0;

    private List<DictFunBean> certTypeList;

    private List<String> certNames;

    public static NormalHolidayFragment newInstance(String typeCode)
    {
        Bundle bundle = new Bundle();
        bundle.putString( HOLIDAY_TAG , typeCode );
        NormalHolidayFragment holidayFragment = new NormalHolidayFragment();
        holidayFragment.setArguments( bundle );
        return holidayFragment;
    }

    @Override
    public int getLayoutId()
    {
        return R.layout.fragment_normal_holiday;
    }

    @Override
    public int getBindingVariable() {
        return 0;
    }

    @Override
    protected void initParameters()
    {
        Bundle args = getArguments();
        String type = "";
        if(  args != null )
        {
            type = args.getString(HOLIDAY_TAG , "");
        }

        if( !StringUtils.isEmpty( type ))
        {
            mHolidayType = GsonUtil.json2Obj( type, HolidayTypeBean.class);
        }
    }

    @Override
    protected void onRetryBtnClick() {

    }

    @Override
    protected void initView(View view)
    {
        vacParam = new VacationParam();
        loading = new LoadingDialog( getActivity(), getString( R.string.loading ) );
        // 选择 证书 等
        pickerDialog = new PickerDialog(getActivity(), (selectStr, position) -> {
            if( pickTag == 1 )
            {
                viewDataBinding.tvCertType.setText( selectStr );
                // 设置 选择的 证书类型 和 ID
                // 更换 证书 休假
                //if( holidayType == changeHolidayType )
                {
                    //设置 证书类型
                    vacParam.setCerttype(certTypeList.get(position).getDict_value());
                    vacParam.setCerttype_id(certTypeList.get(position).getUuid());
                }

            }
            else if( pickTag == 2 )
            {
                viewDataBinding.tvTempReason.setText( selectStr );
            }
        });
        initDataPicker();
        if(ObjectUtils.isNotEmpty( mHolidayType ))
        {
            holidayType = mHolidayType.getApplyType();
            initViewByType(holidayType);
            // 设置 申请休假 类型
            vacParam.setVactiontype(mHolidayType.getVactionType());
            //"a6e91f09-5d1c-4e04-b2c7-0ad39e1c7e9a"
            vacParam.setVactiontype_id(mHolidayType.getVactionTypeId());
        }

        //休假 开始时间
        viewDataBinding.btnStartTimeSelect.setOnClickListener( v -> {
            timeTag = 1;
            datePicker.show( TimeUtil.getTimeStandard( System.currentTimeMillis() ) );
        } );
        //休假 结束时间
        viewDataBinding.btnEndtimeSelect.setOnClickListener( v -> {
            timeTag = 2;
            datePicker.show( TimeUtil.getTimeStandard( System.currentTimeMillis() ) );
        } );

        //港口 选择
        viewDataBinding.btnPortAreaSelect.setOnClickListener( v -> {
            // 去选 港口
            PortActivity.start( getActivity() );

        } );
        // 延迟 休假 开始 时间
        viewDataBinding.btnSelectDelayStartTime.setOnClickListener( v -> {
            timeTag = 3;
            datePicker.show( TimeUtil.getTimeStandard( System.currentTimeMillis() ) );
        } );
        //延迟 休假 结束 时间
        viewDataBinding.btnSelectDelayEndTime.setOnClickListener( v -> {
            timeTag = 4;
            datePicker.show( TimeUtil.getTimeStandard( System.currentTimeMillis() ) );
        } );

        // 证书休假 选择 证书
        viewDataBinding.btnSelectCertType.setOnClickListener(v -> {
            pickTag = 1;
            //pickerDialog.showPickContent(new String[]{"海员证","健康证","其他证书"});
            if(  certNames != null && !certNames.isEmpty()  )
            {
                //已经 获取过 证书类型了
                pickerDialog.showPickContent(certNames);
            }
            else
            {
                loading.show();
                viewModel.queryCertTypeList();
            }
        });
        //临时休假 选择原因
        viewDataBinding.btnSelectTempReason.setOnClickListener( v -> {
            pickTag = 2;
            pickerDialog.showPickContent(new String[]{"探亲","病假"});
        } );

        //提交 休假
        viewDataBinding.btnNext.setOnClickListener(v -> {
            int totalHours = 0;
            String startTime = viewDataBinding.tvStartTime.getText().toString();
            String endTime = viewDataBinding.tvEndTime.getText().toString();

            boolean isTimeRight = ComDataUtils.isEndTimeRight( startTime ,endTime );
            if( !isTimeRight )
            {
                ToastUtils.showShort("选择正确的日期");
                return;
            }
            totalHours = ComDataUtils.getHolidayHoursCount(startTime , endTime);
            if( holidayType == delayHolidayType )
            {
               //延期休假 时
                String startDelay = viewDataBinding.tvDelayStartTime.getText().toString();
                String endDelay = viewDataBinding.tvDelayEndTime.getText().toString();

                boolean isRight = ComDataUtils.isEndTimeRight( startDelay ,endDelay );
                if( !isRight )
                {
                    ToastUtils.showShort("选择正确的日期");
                    return;
                }
               totalHours = ComDataUtils.getHolidayHoursCount(startDelay , endDelay);
            }

            // 设置 交接人
            vacParam.setHandover_user("");
            vacParam.setHandover_user_id("");



            // 休假人 信息
            vacParam.setVacationWorkerInfo( GlobalConfig.getInstance().getUserInfo() );

            vacParam.setCreator( GlobalConfig.getInstance().getUserInfo().getUserTrueName());
            vacParam.setCreateID( GlobalConfig.getInstance().getUserInfo().getUuid() );

            String remarkStr = viewDataBinding.etHolidayReason.getText().toString();
            vacParam.setRemark( remarkStr );
            LogUtils.e("totalHours  = " + totalHours);
            // 设置 请假的 总 小时数
            vacParam.setTotal(totalHours);

            vacParam.setStatus("1");

            loading.show();
            viewModel.applyUserVacation(vacParam);

        } );

        // 没有 公司信息 就不能 点击
        if(  StringUtils.isEmpty( GlobalConfig.getInstance().getUserInfo().getCompany_id() )    )
        {
            viewDataBinding.btnNext.setEnabled( false );
        }


        LiveEventBus.get(PortActivity.PORT_RESULT , PortBean.class)
                    .observeSticky( this , portBean -> {
                        // 获取到 港口 信息
                        selectPort = portBean;

                        viewDataBinding.tvArea.setText( selectPort.getName() );
                        //设置 港口
                        vacParam.setPort( selectPort.getName());
                        //"b26c428e-863b-11eb-b45c-5254006b78b4"
                        vacParam.setPort_id( selectPort.getUuid() );

                    } );

    }

    private void initViewByType(int type)
    {
        String today = TimeUtil.getTimeYMDHM( System.currentTimeMillis() );
        viewDataBinding.tvStartTime.setText( today );
        viewDataBinding.tvEndTime.setText( today );
        viewDataBinding.tvDelayStartTime.setText( today );
        viewDataBinding.tvDelayEndTime.setText( today );

        switch (type)
        {
            case 1:
                viewDataBinding.rlTempHolidayLayout.setVisibility(View.GONE);
                viewDataBinding.rlZhengshuHolidayLayout.setVisibility(View.GONE);
                viewDataBinding.rlDelayStartTimeLayout.setVisibility(View.GONE);
                viewDataBinding.rlDelayEndTimeLayout.setVisibility(View.GONE);
                break;
            case 2:
                viewDataBinding.rlTempHolidayLayout.setVisibility(View.VISIBLE);
                viewDataBinding.rlZhengshuHolidayLayout.setVisibility(View.GONE);
                viewDataBinding.rlDelayStartTimeLayout.setVisibility(View.GONE);
                viewDataBinding.rlDelayEndTimeLayout.setVisibility(View.GONE);
                break;
            case 3:
                viewDataBinding.rlTempHolidayLayout.setVisibility(View.GONE);
                viewDataBinding.rlZhengshuHolidayLayout.setVisibility(View.GONE);
                viewDataBinding.rlDelayStartTimeLayout.setVisibility(View.VISIBLE);
                viewDataBinding.rlDelayEndTimeLayout.setVisibility(View.VISIBLE);
                break;
            case 4:
                viewDataBinding.rlTempHolidayLayout.setVisibility(View.GONE);
                viewDataBinding.rlZhengshuHolidayLayout.setVisibility(View.VISIBLE);
                viewDataBinding.rlDelayStartTimeLayout.setVisibility(View.GONE);
                viewDataBinding.rlDelayEndTimeLayout.setVisibility(View.GONE);
                break;
            default:
                viewDataBinding.rlTempHolidayLayout.setVisibility(View.GONE);
                viewDataBinding.rlZhengshuHolidayLayout.setVisibility(View.GONE);
                viewDataBinding.rlDelayStartTimeLayout.setVisibility(View.GONE);
                viewDataBinding.rlDelayEndTimeLayout.setVisibility(View.GONE);
                break;
        }
    }

    private void initDataPicker()
    {
        datePicker = new CustomDatePicker(getActivity(), new CustomDatePicker.ResultHandler() {
            @Override
            public void handle(String time) {

                // 时间 精确到 分

                // 开始 结束时间   TimeUtil.getTimeYMDHS2YMD( time )
                switch ( timeTag  )
                {
                    case  1:
                        // 开始时间
                        String startDate =  time ;
                        viewDataBinding.tvStartTime.setText( startDate  );
                        vacParam.setStartdate( startDate );
                        break;

                    case  2:
                        // 结束时间
                        String endDate = time ;
                        viewDataBinding.tvEndTime.setText( endDate  );
                        vacParam.setEnddate( endDate );
                        break;
                    case  3:
                        // 延迟开始时间
                        String delayStartDate = time ;
                        viewDataBinding.tvDelayStartTime.setText( delayStartDate  );
                        vacParam.setDelay_startdate( delayStartDate );
                        break;
                    case  4:
                        // 延迟结束时间
                        String delayEndDate = time ;
                        viewDataBinding.tvDelayEndTime.setText( delayEndDate  );
                        vacParam.setDelay_enddate( delayEndDate );
                        break;
                }
                // 获取时间 一个long值
                //long resultTime = TimeUtil.parseDate(time).getTime();
                LogUtils.e("CustomDatePicker", time + "  时间= " + TimeUtil.getTimeYMDHS2YMD( time ));
            }
        } , CustomDatePicker.getTimeStandard(System.currentTimeMillis()),CustomDatePicker.getTimeStandard((System.currentTimeMillis() + 1000*60*60*24*365)));

        // 初始化日期格式请用：yyyy-MM-dd HH:mm
        // HH:mm，否则不能正常运行 //false 不显示时和分
        datePicker.showSpecificTime(true);
        datePicker.setIsLoop(true); // false 不允许循环滚动
        /*
         * //currentTime.setText(now); datePicker = new CustomDatePicker(this, new
         * CustomDatePicker.ResultHandler() {
         * @Override public void handle(String time) { // 回调接口，获得选中的时间 //currentTime.setText(time);
         * } }, "2010-01-01 00:00", now); // 初始化日期格式请用：yyyy-MM-dd HH:mm，否则不能正常运行
         * datePicker.showSpecificTime(true); // 显示时和分 datePicker.setIsLoop(true); // 允许循环滚动
         */
    }

    @Override
    protected void lazyLoad()
    {
        // 申请 结果
        viewModel.getVacApplyResult().observe( this , result -> {
            loading.hide();
            if( result.isSuccess() )
            {
                PushToast.getInstance(getActivity()).show( PushToast.SUBMIT_SUCCESS );
                getActivity().finish();
            }
            else
            {
                ToastUtils.showShort( result.getMsg() );
            }
        } );

        //查询到证书类型
        viewModel.getCertTypeResult().observe(this,result -> {
            loading.hide();
            if( result.isSuccess() )
            {
                certTypeList = result.getData();
                certNames = formatCertNames(certTypeList);
                pickerDialog.showPickContent(certNames);
            }
            else
            {
                ToastUtils.showShort( result.getMsg()  );
            }
        });
    }

    private List<String> formatCertNames(List<DictFunBean> certList)
    {
        List<String> certs = new ArrayList<String>();
        if( certList != null && !certList.isEmpty() )
        {
            for (DictFunBean funBean : certList)
            {
                certs.add( funBean.getDict_value() );
            }
        }
        return certs;
    }

    @Override
    public void onDestroy()
    {
        super.onDestroy();
        loading.dismiss();
    }
}
